﻿using System;
using System.Collections.Generic;
using System.Data;

namespace Core.Library
{
    public class ObjectHelper
    {
        public static T FillObject<T>(IDataReader dr)
        {

            T objTarget = default(T);
            if (dr == null) return objTarget;
            try
            {
                if (dr.Read())
                {
                    objTarget = Activator.CreateInstance<T>();
                    var objProperties = objTarget.GetType().GetProperties();
                    foreach (var property in objProperties)
                    {
                        if (property.CanWrite && !Convert.IsDBNull(dr[property.Name]))
                        {
                            property.SetValue(objTarget, dr[property.Name], null);
                        }
                    }
                }
            }
            finally
            {
                dr.Close();
            }
            return objTarget;
        }
        public static List<T> FillCollection<T>(IDataReader dr)
        {
            var list = new List<T>();
            if (dr == null) return list;
            try
            {
                while (dr.Read())
                {
                    var objTarget = Activator.CreateInstance<T>();
                    var objProperties = objTarget.GetType().GetProperties();
                    foreach (var property in objProperties)
                    {
                        var lazy = new LazyInitAttribute(false);
                        var objs = property.GetCustomAttributes(true);
                        if (objs.Length > 0)
                            lazy = (LazyInitAttribute)objs[0];
                        if (lazy.IsLazyInit) continue;
                        if (property.CanWrite && !Convert.IsDBNull(dr[property.Name]))
                        {
                            property.SetValue(objTarget, dr[property.Name], null);
                        }
                    }
                    list.Add(objTarget);
                }
            }
            finally
            {
                dr.Close();
            }
            return list;
        }
    }
}